# 导入库
import pandas as pd
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')

class ClusterUtils(object):
    """
    聚类工具类
    """
    def __init__(self):
        self.df = pd.read_csv('tourist_agency_visitors.csv')

    def get_cluster(self):
        """
        获取聚类结果
        """
        # 提取特征并标准化
        features = self.df[['out_province_ratio', 'elderly_ratio', 'non_weekend_visitors']]
        scaler = StandardScaler()
        scaled_features = scaler.fit_transform(features)
        # 聚类
        kmeans = KMeans(n_clusters=4, random_state=42)
        labels = kmeans.fit_predict(scaled_features)
        self.df['cluster'] = labels
        # 查看聚类结果
        print(self.df[['tourist_agency_name', 'cluster']])
        # 查看聚类中心
        centers = scaler.inverse_transform(kmeans.cluster_centers_)
        print(pd.DataFrame(centers, columns=features.columns))
        # 保存结果
        self.df.to_csv('tourist_agency_visitors_clustered.csv', index=False)
        # 将聚类中心转换为DataFrame
        center_df = pd.DataFrame(centers, columns=features.columns)
        center_df['cluster'] = [f'Cluster {i+1}' for i in range(centers.shape[0])]
        # 转换为长表为（适合seaborn）
        center_long = center_df.melt(id_vars='cluster', var_name='feature', value_name='value')
               # 绘制分组柱状图
        # 设置字体
        plt.rcParams['font.sans-serif'] = ['SimHei']
        plt.rcParams['axes.unicode_minus'] = False
        color = ['#ff7f0e', '#ff7f9e', '#2c8b2c', '#466278']
        plt.figure(figsize=(10, 6))
        sns.barplot(x='feature', y='value', hue='cluster', data=center_long, palette=color)
        plt.title('聚类中心特征值对比')
        plt.xlabel('特征')
        plt.legend(title='簇', bbox_to_anchor=(1.05, 1), loc='upper left')
        # 添加数值标签
        for p in plt.gca().patches:
            height = p.get_height()
            plt.gca().text(p.get_x() + p.get_width() / 2., height, f'{height:.2f}', ha='center')
        plt.tight_layout()
        plt.show()

if __name__ == '__main__':
    cu = ClusterUtils()
    cu.get_cluster()
    # cu.get_cluster()
